<template>
  <el-dialog title="角色分配" :close-on-click-modal="false" :show-close="false"
             :visible.sync="assignShow" width="40%" @open="handleShow">
    <el-form>
      <el-form-item>
        <el-select v-model="selectRoleId" placeholder="请选择角色">
          <el-option v-for="item in notRoles" :key="item.id" :label="item.roleName" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addRole">添加</el-button>
        <el-button @click="closeDialog">取消</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="hasRoles" style="width: 100%" border :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }">
      <el-table-column label="已分配的角色">
        <el-table-column prop="id" label="#ID"></el-table-column>
        <el-table-column prop="roleName" label="标签"></el-table-column>
        <el-table-column prop="roleKey" label="权限字符串"></el-table-column>
        <el-table-column label="操作" width="80px">
          <template slot-scope="scope">
            <el-button type="danger" icon="el-icon-delete" size="small"
                       @click="delRole(scope.row.id)" circle>
            </el-button>
          </template>
        </el-table-column>
      </el-table-column>
    </el-table>

  </el-dialog>
</template>

<script>
import {userHasRoles, userNotHasRoles} from "@/api/systrm-role";
import {assignRole, deleteRole} from "@/api/system-user";

export default {
  data() {
    return {
      selectRoleId: '',
      notRoles: [],
      hasRoles: []
    }
  },
  methods: {
    handleShow() {
      this.getUserHasRoles()
      this.getUserNotRoles()
    },
    addRole() {
      const userRole = {
        userId: this.id,
        roleId: this.selectRoleId
      }

      assignRole(userRole).then(res => {
        this.$message.success('分配成功')
        this.getUserHasRoles()
        this.getUserNotRoles()
      }).catch(err => {
        this.$message.error('分配失败')
      })
    },
    delRole(id) {
      console.log(11)
      const userRole = {
        userId: this.id,
        roleId: id
      }
      deleteRole(userRole).then(res => {
        this.$message.success('删除成功')
        this.getUserHasRoles()
        this.getUserNotRoles()
      }).catch(err => {
        this.$message.error('删除失败')
      })
    },
    closeDialog() {
      this.$emit('closeDialog')
    },
    getUserNotRoles() {
      userNotHasRoles(this.id).then(res => {
        this.notRoles = res
      }).catch(err => {
      })
    },
    getUserHasRoles() {
      userHasRoles(this.id).then(res => {
        this.hasRoles = res
      }).catch(err => {
      })
    }
  },
  props: {
    assignShow: {
      type: Boolean,
      default: false
    },
    id: {
      type: Number | String,
      default: 0
    }
  },
}
</script>

<style scoped>

</style>
